package ru.spbu.math.seabattle.server.jms.gui;

import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JFrame;

import ru.spbu.math.seabattle.server.jms.SuperMegaServerWrapper;

public class ServerGUI extends JFrame {

	private static final long serialVersionUID = 1L;
	
	private static final Rectangle FRAME_RECTANGLE = new Rectangle(200, 200, 200, 200);
	private static final Rectangle BUTTON_RECTANGLE = new Rectangle(50, 30, 100, 40);
	
	private final SuperMegaServerWrapper server;
	
	private boolean running = false;
	
	public ServerGUI(SuperMegaServerWrapper serverWrapper) {
		super("SeaBattle Server");
		
		this.server = serverWrapper;
		
		final JButton button = new JButton("Start");
		button.setBounds(BUTTON_RECTANGLE);
		
		this.setBounds(FRAME_RECTANGLE);
		this.getContentPane().setLayout(null);
		this.getContentPane().add(button);
		
		button.addMouseListener(
				new MouseListener() {

					@Override
					public void mouseClicked(MouseEvent arg0) {
						try {
							if (running) {
								server.shutdown();
								running = false;
								button.setText("Start");
								System.out.println("SERVER SHUTDOWN");
							} else {
								server.start();
								running = true;
								button.setText("Stop");
								System.out.println("SERVER IS RUNNING...");
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					@Override public void mouseEntered(MouseEvent arg0) {}
					@Override public void mouseExited(MouseEvent arg0) {}
					@Override public void mousePressed(MouseEvent arg0) {}
					@Override public void mouseReleased(MouseEvent arg0) {}
					
				}
			);
		
		this.addWindowListener(
				new WindowListener() {

					@Override public void windowActivated(WindowEvent arg0) {}
					@Override public void windowClosed(WindowEvent arg0) {}

					@Override
					public void windowClosing(WindowEvent arg0) {
						try {
							arg0.getWindow().dispose();
							if (running) server.shutdown();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					@Override public void windowDeactivated(WindowEvent arg0) {}
					@Override public void windowDeiconified(WindowEvent arg0) {}
					@Override public void windowIconified(WindowEvent arg0) {}
					@Override public void windowOpened(WindowEvent arg0) {}
					
				}
			);
		
		this.setVisible(true);
	}
}
